<template>
  <div :style="{height: '100%',width: '100%'}" />
</template>
<script>
import * as echarts from 'echarts'
export default {
  name: 'CompanyBarChart',
  props: {
    xAxisData: { type: Array, default: null },
    yAxisData: { type: Array, default: null },
    legendArray: { type: Array, default: null }
  },
  data: () => ({
    chart: null
  }),
  watch: {
    yAxisData: {
      handler(val) {
        if (this.chart) this.chart.dispose()
        this.chartInit()
      },
      immediate: true,
      deep: true
    },
    xAxisData: {
      handler(val) {
        if (this.chart) this.chart.dispose()
        this.chartInit()
      },
      immediate: true,
      deep: true
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize)
  },
  mounted() {
    window.addEventListener('resize', this.resize)
    this.chartInit()
  },
  methods: {
    chartInit() {
      const promise = new Promise(res => {
        res()
      })
      promise.then(() => {
        this.chart = echarts.init(this.$el)
        this.setChart()
      })
    },
    setChart() {
      this.chart.showLoading()
      const barOption = {
        title: {
          subtext: '次/小时：'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data: this.xAxisData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: []
      }
      barOption.legend.data = this.legendArray
      const ar = this.yAxisData || {
        name: '',
        type: 'bar',
        data: [2.0, 4.9, 7.0, 23.2],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ yAxis: 20, name: '平均值' }]
        }
      }
      barOption.series = ar
      this.chart.setOption(barOption)
      this.chart.hideLoading()
    },
    resize() {
      this.chart.resize()
    }
  }
}
</script>
